<?php

namespace brand\page;
use brand\Brand;
use brand\build\Columns;
use brand\logic\BrandHelper;
use brand\logic\Config;
use brand\tools\Functions;
use brand\traits\BrandAdmin;
use surface\Component;
use surface\Factory;
use function url;

class Table  extends Page
{



    public static function init($curdName)
    {
        self::$SurfaceTable = Factory::table();
        self::setAddUrl();
        self::setEditUrl();
        self::setDeleteUrl();
        self::setUpdateUrl();
        self::setTableDataUrl();
        self::setExportUrl();
        self::$page_size = Config::$page_size;
        self::$header_buttons = Config::$header_buttons;
        self::$right_buttons = Config::$right_buttons;
        self::$curdName = $curdName;
        self::$custom_button = [];
        self::$custom_button_header = [];
        //设置静态方法
        self::setPageConfig();
    }

    public static function setHeaderButton()
    {
        //新增按钮
        if (in_array('add',self::$header_buttons)){
            self::$custom_button_header['edit'] =  Brand::Builder()->build_button('','el-icon-plus')->button_url(self::$add_url)->button_data([])
                ->button_props(self::buttonProps(''))
                ->build();
        }

        //刷新按钮
        self::$custom_button_header['refresh'] =  Brand::Builder()->build_button('','el-icon-refresh','refresh')
            ->button_props(self::buttonProps(''))
            ->build();

        //删除按钮
        if (in_array('delete',self::$header_buttons)) {

            self::$custom_button_header['delete'] =  Brand::Builder()->build_button('','el-icon-delete','submit')
                ->button_url(self::$delete_url)
                ->button_pk(self::$pk)
                ->button_confirm('确认要删除选择的数据？')
                ->button_props(self::buttonProps('','danger'))
                ->build();

        }
        //搜索按钮
        if (in_array('search',self::$header_buttons)) {
            self::$custom_button_header['search'] =  Brand::Builder()->build_button('','el-icon-search','search')
                ->button_props(self::buttonProps(''))
                ->build();
        }


        //导出
        if (in_array('export',self::$header_buttons)) {
            self::$custom_button_header['export'] =  Brand::Builder()->build_button('','el-icon-top','export')
                ->button_url(url('export',request()->get())->build())
                ->button_props(self::buttonProps('导出'))
                ->build();
        }


        //CURD修改按钮
        if (BrandHelper::checkCurdName(self::$curdName,true) && app()->isDebug()){
            self::$custom_button_header['curd'] =  Brand::Builder()->build_button('','el-icon-s-tools')
                ->button_url(url(BrandHelper::getAdminName().'/curd/tableFields',['addon'=>self::$curdConfig['addon']['name'] ?? ''])->build())
                ->button_data(['table'=>self::$curdName])
                ->button_props(self::buttonProps('CURD设置'))
                ->build();
        }
    }



    /**
     * 设置头部
     */
    public static function header()
    {

        //设置按钮
        self::setHeaderButton();

        $header = $top = array();

        if (self::$title) $top[] = (Brand::Component())->el('div')->class('title')->children([self::$title]);
        if (self::$describe) $top[] = (Brand::Component())->el('p')->class('describe')->children([self::$describe]);

        if ($top) $header[] = (Brand::Component())->el('p')->children($top);





        $buttons = \brand\components\Component::Button()->buildButtons(self::$custom_button_header);
        $header = array_merge($header,$buttons);

        // 添加js代码到全局
        $exportUrl = self::$exportUrl;
        $mixinJs = self::$mixinJs;
        $mixin = <<<JS
    <script>
        var export_url = '$exportUrl';
        $mixinJs
    </script>
JS;
        self::$SurfaceTable->addScript($mixin);
        self::$SurfaceTable->addScript(BrandHelper::getMixin('table'));

        $header[] = (Brand::Component())->el('div')->class('statistics');

        return Brand::Component()->el('div')->children( $header );
    }


    /**
     * 构建表格
     * @param $columns
     * @return array
     */
    public static function buildTable($columns)
    {

        $table = self::$SurfaceTable;
        //选中key
        $selection_key = request()->param('selection_key');
        if (!$selection_key || $selection_key == 'id'){
            $selection_key = self::$pk;
        }
        $column_arr['_selection'] = $table->selection($selection_key);
        foreach ($columns as $key => $column) {

            if (is_object($column)){
                $column_arr[$key] = $column;
                continue;
            }

            if (!self::columnsTableIsShow($column)) continue;

            $table_conf = $column['table'] ;
            //方法名称
            $method = $table_conf['method'] ?? 'column';
            $this_column = $table->{$method}($key,$column['title']);
            $action_type= $table_conf['action_type'] ?? 'input';
            $ClassName = Config::BRAND_NAMESPACE . Functions::toCamelCase($action_type);
            if (class_exists($ClassName)){
                $ClassObject = new $ClassName($column,[]);
                $ClassObject->field = $key;
                $ClassObject->pk = self::$pk;
                $ClassObject->buildColumns();
                $this_column = $ClassObject->Table($this_column,self::class);

            }


            $column_arr[$key] = $this_column;
        }

        //自定义按钮


        //操作按钮
        if (in_array('edit',self::$right_buttons)){

            self::$custom_button[] = Brand::Builder()->build_button('编辑','el-icon-edit')
                ->button_visible(self::$visible_edit)
                ->button_url(self::$edit_url)
                ->button_data([self::$pk])
                ->button_props(self::buttonProps('编辑','primary','mini2'))
                ->build();

        }

        if (in_array('delete',self::$right_buttons)){
            self::$custom_button[] = Brand::Builder()->build_button('删除','el-icon-delete','confirm')
                ->button_confirm('确认删除数据?')
                ->button_visible(self::$visible_edit)
                ->button_url(self::$delete_url)
                ->button_data([self::$pk])
                ->button_props(self::buttonProps('删除','danger','mini2'))
                ->build();

        }

        foreach (self::$custom_button as $key => $item) {
            self::$custom_button[$key] = \brand\components\Component::Button()->build( $item );
        }

        if (self::$right_buttons || self::$custom_button){
            $column_arr['_options'] = $table->column('options', '操作')->props('fixed', 'right')->scopedSlots( self::$custom_button );
        }


        return $column_arr;
    }
    public static function pagination(): ?Component
    {
        return Brand::Component()->props(
            [
                'async' => [
                    'url' => self::$table_data_url,
                ],
            ],''
        )->props('hide-on-single-page',true)->props('page-size',self::$page_size);
    }


    public static function columnsTableIsShow($column)
    {
        if(!isset($column['table']) || $column['table'] === false) {
            return false;
        }
        if (isset($column['table']['status']) && !$column['table']['status']){
            return false;
        }
        //判断自动写入时间
        if ( isset($column['form']['delete_time'])) return false;

        return true;
    }


    public static function createTable($columns = [])
    {
        $table = new self();
        Columns::setConfig($columns);
        return $table;
    }


    public function setDataUrl($url = "")
    {
        $this::$table_data_url = $url;
        return $this;
    }

    public function setSearch($search_columns = [])
    {
        $this::$SurfaceTable->search($search_columns);
        return $this;
    }

    public function setTableHeader($header = [])
    {
        self::$header_buttons = [];
        $this::$custom_button_header = $header;
        return $this;
    }

    public function setTableRight($right = [])
    {
        $this::$right_buttons = $right;
        return $this;
    }


    public function tableView()
    {
        //设置头信息
        $this::$SurfaceTable->header($this::header());
        //设置行数据
        $this::$SurfaceTable->columns($this::buildTable(Columns::getConfig()));
        //设置分页
        $this::$SurfaceTable->pagination( $this::pagination());

        //显示页面
        return $this::$SurfaceTable->view();
    }


}